package com.zjxny.jobs;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.zjxny.service.CarInfoService;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.erupt.core.annotation.EruptHandlerNaming;
import xyz.erupt.job.handler.EruptJobHandler;

//获取车辆详情 更新使用性质和合证上面的数据
@Slf4j
@Service
@EruptHandlerNaming("更新车辆合格证")
public class UpdateCarCertJob implements EruptJobHandler {
	
	@Resource
	JdbcTemplate jdbcTemplate;
	
	@Resource
	CarInfoService carInfoService;
	
	@Value("${traffic.sleep:1000}")
	Long sleepTime;
	
	@Override
	public String exec(String code, String param) {
		String sql = "select id,account_info_id uid,xh from car_info where is_not_operation=1";
		List<Map<String,Object>> lists = jdbcTemplate.queryForList(sql);
		for(Map<String,Object> map: lists) {
			String xh =(String) map.get("xh");
			Long id = (Long) map.get("id");
			Long uid = (Long) map.get("uid");
			
			String certJson;
			try {
				certJson = carInfoService.getCert(uid, xh);
				JSONObject certNode = JSONUtil.parseObj(certJson);
				if(certNode.containsKey("result") && certNode.getByPath("$.result.clsbdh")!=null) {
					String syxzStr = certNode.getByPath("$.result.syxzStr",String.class);
					String jyhgbzbh = certNode.getByPath("$.result.jyhgbzbh",String.class);
					String cjdw = certNode.getByPath("$.result.cjdw",String.class);
					
					String uSql = String.format("update car_info set syxz_str='%s', jyhgbzbh='%s',cjdw='%s' where id=%d",syxzStr,jyhgbzbh,cjdw,id );
					int affectNum = jdbcTemplate.update(uSql);
					log.info("carId={},affectNum={}",id,affectNum);
				}
				if(sleepTime>0) {					
					long random = RandomUtil.randomLong(sleepTime);
					try {
						Thread.sleep(random);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
